<!-- 富文本编辑器 -->
<template>
  <div class="h100">
    <n-button type="primary" size="medium" @click="photoShowModal = true" v-if="ishowVideo">点击插入视频</n-button>
    <div :id="fwbid" class="fwbclass "></div>


    <n-modal v-model:show="photoShowModal" preset="card" class="Stock-diagnosis">
      <template #header>
        <div>视频</div>
      </template>
      <div>
        <photoGallery @getImg="getImg" :types="'视频' + uid" accept=".mp4"></photoGallery>
      </div>
      <template #action>
        <div class="tr">
          <n-button @click="photoShowModal = false" size="medium"> 取消 </n-button>
          <n-button class="ml10" type="primary" @click="setImg" size="medium"> 确定 </n-button>

        </div>
      </template>
    </n-modal>

    <n-modal v-model:show="wdfdsfdsf" preset="card" class="dsfdsfretrtrt">
      <template #header>
        <div>上传word文件</div>
      </template>
      <div class="vertical-center">
        <div class="xzczxcrtry vertical-center sz pr">
          点击上传word文件
          <input type="file"  class="xzcdzffsdtrt" @change="handleFileChange" accept=".docx"/>
        </div>
      </div>
      <template #action>
        <div class="tr">
          <n-button> 取消 </n-button>
        </div>
      </template>
    </n-modal>

  </div>
</template>
<script lang='ts' setup>
import { ref, onMounted, nextTick } from "vue";
import { apiUrl } from "../../util/config";
import photoGallery from "./photoGallery";
import mammoth from 'mammoth';
const photoShowModal = ref(false)
const wdfdsfdsf = ref(false)
const props = defineProps({
  ishowVideo: { type: Boolean },
  htmlNr: { type: String },
});
const uid = localStorage.id
const pluginse = `
 undo 
 redo 
 fontsizeselect  
 styleselect 
 forecolor  
 lineheight  
 italic 
 bold 
 alignleft 
 aligncenter 
 alignright 
 alignjustify  
 removeformat 
 table 
 image 
 bullist 
 numlist 
 fullscreen 
  pagebreak 
 preview 
 print 
 mycustombutton
 code

 `

const fontsize = []
for (let i = 12; i < 100; i++) {
  fontsize.push(i + 'px')
}
const fwbid = "ids" + new Date().getTime()
nextTick(() => {
  setTimeout(() => {
    window.tinymce.init({
      selector: '#' + fwbid,
      plugins: "code table image  link imagetools contextmenu  lists advlist fullscreen hr pagebreak preview print searchreplace  mycustombutton",
      language: 'zh_CN',
      toolbar: pluginse,
      images_upload_url: apiUrl + 'public/Upimgfwb',
      fontsize_formats: fontsize.join(' '),
      setup: function (editor) {
        editor.ui.registry.addButton('mycustombutton', {
          icon: 'fdssderrttr5t', // 使用图标，确保你的图标在tinyMCE的图标库中或通过其他方式提供
          tooltip: '点击上传word文件', // 按钮的提示信息
          onAction: function () {
            wdfdsfdsf.value = true
          }
        });
      },
      file_picker_callback: function (callback, value, meta) {
        var filetype = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
        //后端接收上传文件的地址
        var upurl = apiUrl + 'public/Upimg/upfile';
        //为不同插件指定文件类型及后端地址
        switch (meta.filetype) {
          case 'image':
            filetype = '.jpg, .jpeg, .png, .gif';
            upurl = 'upimg.php';
            break;
          case 'media':
            filetype = '.mp3, .mp4';
            upurl = 'upfile.php';
            break;
          case 'file':
          default:
        }
        //模拟出一个input用于添加本地文件
        var input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', filetype);
        input.click();
        input.onchange = function () {
          var file = this.files[0];
          var xhr, formData;
          xhr = new XMLHttpRequest();
          xhr.withCredentials = false;
          xhr.open('POST', upurl);
          xhr.onload = function () {
            let jjhxsd = ""
            try {
              jjhxsd = JSON.parse(xhr.response)
            } catch (e) {

            }
            callback(jjhxsd.data.imgurl, { text: jjhxsd.data.fileName });
            // callback(json.location);
          };
          formData = new FormData();
          formData.append('file', file, file.name);
          xhr.send(formData);

        }
      },
    });
    setTimeout(() => {
      if (props.htmlNr) {
        window.tinyMCE.editors[fwbid].setContent(props.htmlNr)
      }
    }, 500);
  }, 500);
})


defineExpose({
  // 获取富文本内容
  getContent() {
    var cnt = window.tinymce.editors[fwbid].getContent();
    return cnt
  },
  // 获取富文本内容 文本
  gettext() {
    var cnt = window.tinymce.editors[fwbid].getContent({ format: 'text' });
    return cnt
  },

  // 设置富文本内容
  setContent(html) {

    setTimeout(() => {
      window.tinyMCE.editors[fwbid].setContent(html)
    }, 2000);
  }
})
let jjnmnxe = ""
const getImg = (data) => {
  jjnmnxe = data.blur.split("?imageMogr2")[0];
};
const setImg = () => {
  console.log(jjnmnxe);
  window.tinymce.editors[fwbid].insertContent(`<video class="edui-upload-video  vjs-default-skin     video-js" style="width:100%" controls preload="auto" src="${jjnmnxe}" ><source src="${jjnmnxe}" type="video/mp4"></video>`);
  photoShowModal.value = false;
};

const handleFileChange =async (event) =>{
      const file = event.target.files[0];
      if (file) {
        try {
          const result = await mammoth.convertToHtml({ arrayBuffer: await file.arrayBuffer() });
          console.log(result.value);

          window.tinyMCE.editors[fwbid].setContent(result.value)
          wdfdsfdsf.value = false
        } catch (error) {
          console.error('转换出错:', error);
        }
      }
    }
</script>
<style scoped>
.fwbclass {
  height: 100%;
  background: #f8f8f8;
  min-height: 300px !important;
}

.xzczxcrtry {
  width: 200px;
  height: 200px;
  background: #f8f8f8;
}
.xzcdzffsdtrt{
  position: absolute;
  left: 0;
  top: 0;
  z-index: 100;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}
</style>
